﻿// <copyright file="Helper.cs" company="NTalent">
// Copyright (c) 2010, NTalent, Inc. All rights reserved
// </copyright>
// <author>王彦博 符茂松</author>

namespace Net.Ntalent.Action50.Core.Util
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Data.Common;
    using System.Data.Linq;
    using System.Collections.Generic;
    using Net.Ntalent.Action50.DataAccess;
    using Net.Ntalent.Action50.Core.Service;
    using Net.Ntalent.Action50.Core.Dao;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 帮助类,提供各种帮助操作。
    /// </summary>
    ///<author>王彦博</author> 
    /// <copyright>
    /// Copyright (c) 2010, NTalent, Co. Ltd. All rights reserved.
    /// </copyright>
    /// <version>1.0.0</version>  
    public static class Helper
    {
        /// <summary>
        /// 一个常量，代表默认logo的路径
        /// </summary>
        public static string DEFAULT_LANDSCAPE = "images/action_team_photo.jpg";

        /// <summary>
        /// 将一个字符串中的html标签过滤掉并截取一定长度。
        /// </summary>
        /// <param name="length">
        /// 需要截取的字符串长度
        /// </param>
        /// <param name="length">
        /// 需要进行处理的字符串     
        public static string getSubString(string str, int length)
        {
            string content = (str == null || str == "") ? string.Empty : str;
            content = HTMLFilter.Strip(str);
            return content.Length > length ? content.Substring(0, length) : content;
        }

        /// <summary>
        /// 得到某篇news的第一张图片的src值
        /// </summary>
        /// <param name="news">
        /// 欲拉取图片的news实体
        /// </param>
        /// <returns>
        /// 该news第一张图片的src值
        /// </returns>
        public static IList<string> GetImageNamesOfNews(T_NEWS_AND_LOGS news)
        {
            int index = 0;
            IList<string> ImageNames = new List<string>();
            string content = (news.POST_CONTENT == null) ? string.Empty : news.POST_CONTENT;

            while (ImageNames.Count < 1 && index < news.POST_CONTENT.Length - 1)
            {
                index = content.IndexOf("<img", index);
                if (index < 0) return ImageNames;
                index = content.IndexOf("src=") + 5;
                string ImageName = string.Empty;
                while (content.ElementAt(index) != '\"')
                {
                    ImageName += content.ElementAt(index).ToString();
                    index++;
                }
                ImageNames.Add(ImageName);
            }
            return ImageNames;
        }

        /// <summary>
        /// 获取某action的排名情况，返回0代表该action不在前三名
        /// </summary>
        /// <remarks>
        /// 为了在首页对前三名显示特殊效果
        /// </remarks>
        /// <param name="action">
        /// action的ID
        /// </param>
        /// <returns>该action的名次</returns>
        public static int GetTheOrder(T_ACTIONS action)
        {
            ReadOnlyService readOnlyService = new ReadOnlyService();
            IList<T_ACTIONS> actions = readOnlyService.RetrieveRankingList(1, 10);
            int actionCount = actions.Count;

            if (actionCount >= 3 && action.Id == actions.ElementAt(2).Id)
            {
                return 3;
            }
            if (actionCount >= 2 && action.Id == actions.ElementAt(1).Id)
            {
                return 2;
            }
            if (actionCount >= 1 && action.Id == actions.ElementAt(0).Id)
            {
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 获取该action的排名所应该有的class的值
        /// </summary>
        ///<remarks>
        /// 为了在actionList页面对前三名显示特殊标号
        /// </remarks>
        public static string getTheOrderName(T_ACTIONS action)
        {
            ReadOnlyService readOnlyService = new ReadOnlyService();
            IList<T_ACTIONS> actions = readOnlyService.RetrieveRankingList(1, 10);
            int actionCount = actions.Count;

            if (actionCount >= 3 && action.Id == actions.ElementAt(2).Id)
            {
                return "actionrank img3th";
            }
            if (actionCount >= 2 && action.Id == actions.ElementAt(1).Id)
            {
                return "actionrank img2nd";
            }
            if (actionCount >= 1 && action.Id == actions.ElementAt(0).Id)
            {
                return "actionrank img1st";
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取该action的排名所应该有的外围class的值
        /// </summary>
        ///<remarks>
        /// 为了在actionList页面对前三名显示特殊的VIEW图标
        /// </remarks>
        public static string getTheOrderName2(T_ACTIONS action)
        {
            ReadOnlyService readOnlyService = new ReadOnlyService();
            IList<T_ACTIONS> actions = readOnlyService.RetrieveRankingList(1, 10);
            int actionCount = actions.Count;

            if (actionCount >= 3 && action.Id == actions.ElementAt(2).Id)
            {
                return "actionList actionList3";
            }
            if (actionCount >= 2 && action.Id == actions.ElementAt(1).Id)
            {
                return "actionList actionList2";
            }
            if (actionCount >= 1 && action.Id == actions.ElementAt(0).Id)
            {
                return "actionList actionList1";
            }
            return "actionList";
        }

        /// <summary>
        /// 获取该action的排名所应该有的外围class的值
        /// </summary>
        ///<remarks>
        /// 为了在Default页面对投票栏前三名的外框显示特殊样式
        /// </remarks>
        public static string getTheOrderName3(T_ACTIONS action)
        {
            ReadOnlyService readOnlyService = new ReadOnlyService();
            IList<T_ACTIONS> actions = readOnlyService.RetrieveRankingList(1, 10);
            int actionCount = actions.Count;

            if (actionCount >= 3 && action.Id == actions.ElementAt(2).Id)
            {
                return "3th";
            }
            if (actionCount >= 2 && action.Id == actions.ElementAt(1).Id)
            {
                return "2nd";
            }
            if (actionCount >= 1 && action.Id == actions.ElementAt(0).Id)
            {
                return "1st";
            }
            return string.Empty;
        }

        /// <summary>
        /// 获得查询字符串
        /// </summary>
        /// <param name="context">
        /// 从中进行获取的上下文
        /// </param>
        /// <param name="key">
        /// 欲获取的查询字符串名字
        /// </param>
        public static string getQueryString(HttpContext context, string key)
        {
            string value = context.Request.QueryString[key];
            return (value == null || value == "") ? string.Empty : value;
        }

        /// <summary>
        /// 判断投票栏是否已经到达最后一页，是则返回true，否则发挥false
        /// </summary>
        /// <param name="votePage">
        /// 目前的页码(从1开始)
        /// </param>
        /// <returns>判断结果</returns>
        public static bool isLastVotePage(HttpContext context, int votePage)
        {
            int actionCounts = new ReadOnlyService().RetrieveAllAction(0, 0, "id").Count;
            //已经到最后一页了
            if (votePage * 10 >= actionCounts)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 从前十名中获得得票数第n的活动。
        /// </summary>
        /// <returns>排名第n的action实体</returns>
        public static T_ACTIONS getRank(int n)
        {
            IList<T_ACTIONS> actions = new ReadOnlyService().RetrieveRankingList(1, 10);
            return actions.ElementAt(n - 1);
        }

        /// <summary>
        /// 获得某个action的Landscape的id
        /// </summary>
        /// <param name="actionId">
        /// action的ID
        /// </param>
        /// <returns>
        /// 该action的Landscape的id
        /// </returns>
        public static long getActionLandscapeId(long actionId)
        {
            long id = 0;
            IList<T_GALLARY> gallarys = new GallaryDao().RetrieveByAction(actionId, GallaryType.LANDSCAPE, 0, 0, string.Empty);
            if (gallarys.Count > 0)
            {
                id = gallarys.ElementAt(0).Id;
            }
            return id;
        }

        /// <summary>
        /// 根据news或logs的id判断该news或log所属的action的ID
        /// </summary>
        /// <param name="logsAndNewsId">
        /// news或logs的id
        /// </param>
        /// <returns>
        /// 该news或logs所属的action的Id
        /// </returns>
        public static long getActionIdFromNewsAndLogsId(long logsAndNewsId)
        {
            // if (logsAndNewsId == 0) return 0;
            return new ReadOnlyService().RetrieveNewsAndLogs(logsAndNewsId).ACTION_ID;
        }

        /// <summary>
        /// 取某个action的logo的id，若无logo，则返回0。
        /// </summary>
        /// <param name="actionId">
        /// 欲获取其logoId的action的id
        /// </param>
        /// <returns></returns>
        public static long getAvatarIdByAction(long actionId)
        {
            ActionDao actionDao = new ActionDao();
            return
                actionDao.Retrieve(actionId).LOGO == null ? 0 : Convert.ToInt64(actionDao.Retrieve(actionId).LOGO);
        }
        
        /// <summary>
        /// 根据传入的actionId获取该action的name
        /// </summary>
        /// <returns></returns>
        public static string getActionNameById(long actionId)
        {
            string name = new ActionDao().Retrieve(actionId).ACTION_NAME;
            name = getSubString(name, 30);
            return name;
        }

        public static List<T> ExecuteQuery<T>(this DataContext dataContext, IQueryable query)
        {
            DbCommand command = dataContext.GetCommand(query);
            dataContext.OpenConnection();

            using (DbDataReader reader = command.ExecuteReader())
            {
                return dataContext.Translate<T>(reader).ToList();
            }
        }

        private static void OpenConnection(this DataContext dataContext)
        {
            if (dataContext.Connection.State == ConnectionState.Closed)
            {
                dataContext.Connection.Open();
            }
        }


        //去掉script块
        public static string FiltScriptAndStyle(string content)
        {
            if (null == content || 0 == content.Length)
            {
                return string.Empty;
            }
            string[] aryReg ={   
                @"<script(.|\n)+?/script>",   
                @"<link(.|\n)+?/>" 
            };
            string[] aryRep = {   
                "",   
                ""  
              };

            string strOutput = content;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }

            return strOutput;
        }
    }
}
